<!--
街道工单
 * @Author: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @Date: 2025-05-25 16:46:30
 * @LastEditors: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @LastEditTime: 2025-06-02 11:11:23
 * @FilePath: \iam-ui\src\views\disciplinary\workOrder\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="work">
    <div class="work-top">
      <div class="work-top-item">
        <div class="title">本周工单数</div>
        <div class="num">{{ dwCountMap.week }}个工单</div>
      </div>
      <div class="work-top-item">
        <div class="title">本月工单数</div>
        <div class="num">{{ dwCountMap.month }}个工单</div>
      </div>
      <div class="work-top-item">
        <div class="title">本年累计工单数</div>
        <div class="num">{{ dwCountMap.year }}个工单</div>
      </div>
    </div>
    <div class="work-table">
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="工单编号">
          <el-input
            v-model="searchForm.workOrderNumber"
            placeholder="请输入工单编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="工单来源">
          <el-select
            v-model="searchForm.source"
            placeholder="请选择工单来源"
            clearable
          >
            <el-option label="12345" value="12345" />
            <el-option label="公共号" value="公共号" />
            <!-- 可根据实际来源类型补充 -->
          </el-select>
        </el-form-item>
        <el-form-item label="分配日期">
          <el-date-picker
            v-model="searchForm.assignTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placeholder="请选择分配日期区间"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button type="primary" :loading="exportLoading" @click="handleOut">
            {{ exportLoading ? "导出中..." : "导出工单" }}
          </el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" stripe>
        <el-table-column prop="source" label="工单来源" show-overflow-tooltip />
        <el-table-column
          prop="workOrderNumber"
          label="工单编号"
          show-overflow-tooltip
        />
        <el-table-column
          prop="complaintCategoryLevel1"
          label="诉求分类（一级）"
          show-overflow-tooltip
        />
        <el-table-column
          prop="workOrderSubject"
          label="工单主题"
          show-overflow-tooltip
        />
        <!-- 工单内容 -->
        <el-table-column
          prop="workOrderContent"
          label="工单内容"
          show-overflow-tooltip
        />
        <!-- 分配科室 -->
        <el-table-column
          prop="departmentName"
          label="分配科室"
          show-overflow-tooltip
        />
        <el-table-column
          prop="replyContent"
          label="回复建议"
          show-overflow-tooltip
        />
        <!-- <el-table-column prop="mark" label="处理状态" show-overflow-tooltip /> -->
        <el-table-column
          prop="createTime"
          label="分配日期"
          show-overflow-tooltip
        />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button type="text" @click="handleOptions(row, 'view')"
              >查看详情</el-button
            >
            <!-- <el-button
              v-if="row.mark === '已回复'"
              type="text"
              @click="onReplyDrawerClick(row, 'view')"
              >查看回复</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-count">总共 {{ total }} 个项目</span>
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next, jumper, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 抽屉组件 -->
    <reply-drawer
      v-model:visible="replyDrawerVisible"
      :mode="replyDrawerMode"
      :work-order-data="currentAssetData"
      :reply-list="replyList"
      @cancel="handleReplyCancel"
    />
    <detail-drawer
      v-if="drawerVisible"
      v-model:visible="drawerVisible"
      :type="drawerType"
      :asset-data="currentAssetData"
    />
  </div>
</template>

<script setup>
import { onMounted, reactive, defineAsyncComponent, ref } from "vue";
import { ElMessage } from "element-plus";
import {
  getWorkOrderStats,
  getWorkOrderList,
  getReplyList,
  exportWorkOrders,
  getDWCountMap,
} from "./services";
import useUserStore from "@/store/modules/user";
import dayjs from "dayjs";
import ReplyDrawer from "@/components/ReplyDrawer.vue";

const DetailDrawer = defineAsyncComponent(() =>
  import("@/components/DetailDrawer.vue")
);

const userStore = useUserStore();

const exportLoading = ref(false);

const handleOut = async () => {
  try {
    exportLoading.value = true;
    // 传递查询参数
    const params = { ...searchForm };
    if (params.createTimeRange && params.createTimeRange.length === 2) {
      params.beginTime = dayjs(params.createTimeRange[0]).format(
        "YYYY-MM-DD 00:00:00"
      );
      params.endTime = dayjs(params.createTimeRange[1]).format(
        "YYYY-MM-DD 23:59:59"
      );
      delete params.createTimeRange;
    }
    // 过滤分页参数
    delete params.pageNum;
    delete params.pageSize;

    // 过滤掉无值的参数
    const cleanParams = {};
    Object.keys(params).forEach((key) => {
      const value = params[key];
      if (
        value !== undefined &&
        value !== null &&
        value !== "" &&
        !(Array.isArray(value) && value.length === 0)
      ) {
        cleanParams[key] = value;
      }
    });

    const res = await exportWorkOrders(cleanParams);

    // 创建blob对象
    const blob = new Blob([res], { type: "application/vnd.ms-excel" });

    // 创建下载链接
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);

    // 设置文件名，使用当前日期
    const date = new Date();
    const fileName = `工单数据_${date.getFullYear()}${String(
      date.getMonth() + 1
    ).padStart(2, "0")}${String(date.getDate()).padStart(2, "0")}.xlsx`;
    link.download = fileName;

    // 触发下载
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(link.href);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败：", error);
    ElMessage.error("导出失败，请稍后重试");
  } finally {
    exportLoading.value = false;
  }
};

// 统计数据
const statsData = ref({
  待处理: 0,
  本周处理: 0,
  年累计: 0,
});

// 获取统计数据
const fetchStatsData = async () => {
  try {
    const res = await getWorkOrderStats();
    if (res.code === 200) {
      statsData.value = res.data || {
        待处理: 0,
        本周处理: 0,
        年累计: 0,
      };
    } else {
      ElMessage.error(res.msg || "获取统计数据失败");
    }
  } catch (error) {
    console.error("获取统计数据失败：", error);
    ElMessage.error("获取统计数据失败，请稍后重试");
  }
};

// 表格数据
const tableData = ref([]);
const total = ref(0);
// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
// 抽屉控制
const drawerVisible = ref(false);
const drawerType = ref("");
const currentAssetData = ref(null);

// ReplyDrawer相关
const replyDrawerVisible = ref(false);
const replyDrawerMode = ref("reply");
const replyList = ref([]);

// 搜索表单字段精简
const searchForm = reactive({
  workOrderNumber: "", // 工单编号
  source: "", // 工单来源
  assignTimeRange: [], // 分配日期区间
});

const handleOptions = (row, type) => {
  if (type !== "delete") {
    drawerVisible.value = true;
    drawerType.value = type;
    currentAssetData.value = row;
  }
};

const onReplyDrawerClick = async (row, mode) => {
  currentAssetData.value = row;
  replyDrawerVisible.value = true;
  replyDrawerMode.value = mode;
  if (mode === "view") {
    // 获取工单回复列表
    const departmentId = userStore.dept.deptId;
    const orderId = row.id || row.orderId;
    const res = await getReplyList({ orderId, departmentId });
    if (res.code === 200) {
      replyList.value = res.rows || res.data || [];
    } else {
      replyList.value = [];
    }
  } else {
    replyList.value = [];
  }
};

const handleReplyCancel = () => {
  replyDrawerVisible.value = false;
};

// 获取表格数据
const fetchTableData = async () => {
  try {
    let params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      departmentId: userStore.dept.deptId,
      ...searchForm,
    };
    // 处理分配日期区间
    if (params.assignTimeRange && params.assignTimeRange.length === 2) {
      params.params = {
        beginTime: dayjs(params.assignTimeRange[0]).format(
          "YYYY-MM-DD 00:00:00"
        ),
        endTime: dayjs(params.assignTimeRange[1]).format("YYYY-MM-DD 23:59:59"),
      };
      delete params.assignTimeRange;
    }
    const res = await getWorkOrderList(params);
    if (res.code === 200) {
      tableData.value = res.rows || [];
      total.value = res.total || 0;
    } else {
      ElMessage.error(res.msg || "获取列表数据失败");
    }
  } catch (error) {
    console.error("获取列表数据失败：", error);
    ElMessage.error("获取列表数据失败，请稍后重试");
    tableData.value = [];
    total.value = 0;
  }
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchTableData();
};
// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTableData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
};

// 纪工委统计数据
const dwCountMap = ref({ week: 0, year: 0, month: 0 });

onMounted(() => {
  fetchStatsData();
  fetchTableData();
  // 获取纪工委统计数据，传递 departmentId
  getDWCountMap({ departmentId: userStore.dept.deptId }).then((res) => {
    if (res.code === 200 && res.data) {
      dwCountMap.value = res.data;
    }
  });
});
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
